package org.jeecg.modules.system.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.google.gson.JsonObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.apache.shiro.crypto.hash.Hash;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.util.AESUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import org.apache.commons.codec.binary.Base64;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;

import java.util.*;

/**
 * @Author scott
 * @since 2018-12-17
 */
@RestController
@RequestMapping("/mini")
@Api(tags="微信小程序用户登录")
@Slf4j
public class MiniLoginController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ISysRoleService sysRoleService;


    /**
     * 通过手机号获取用户信息
     * @param phone
     * @return
     */
    @RequestMapping("/getUserByPhone")
    public Result<?> getUserByPhone(String phone) {
        Result<SysUser> result = new Result<>();
        SysUser sysUser = sysUserService.getUserByPhone(phone);
        result.setResult(sysUser);
        return result;
    }
    //接口有问题，待优化
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result<?> miniLogin(String encryptedData, String iv, String sessionKey) {
        String phone = "";
        System.out.println(encryptedData);
        System.out.println(iv);
        System.out.println(sessionKey);
        //借助AES工具类进行解析
        AESUtils aesUtils = new AESUtils();
        try {
            byte[] resultBytes = aesUtils.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
            if (resultBytes != null && resultBytes.length > 0) {
                String phoneStr = new String(resultBytes, "UTF-8");
                System.out.println(phoneStr);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("data", phoneStr);
                phone = jsonObject.getJSONObject("data").getString("phoneNumber");
                System.out.println(phone);
            }
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //获取手机号，从数据库中拿到当前数据
        SysUser sysUser = sysUserService.getUserByPhone(phone);
        JSONObject obj = new JSONObject();
        Result<JSONObject> result = new Result<JSONObject>();
        if (sysUser != null) {
            System.out.println(sysUser);
            String syspassword = sysUser.getPassword();
            String username = sysUser.getUsername();
            // 生成token
            String token = JwtUtil.sign(username, syspassword);
            // 设置token缓存有效时间
            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
            redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000);


            obj.put("token", token);
            obj.put("userInfo", sysUser);
            obj.put("sysAllDictItems", sysDictService.queryAllDictItems());
            result.setResult(obj);
            result.success("登录成功");
        }else{
            result.setCode(500);
            result.setMessage("用户不存在");
        }
        return result;
    }

    @RequestMapping(value = "/getLongCode", method = RequestMethod.GET)
    public Result<?> getLongCode(String code) {
        System.out.println(code);
        String appid = "wx0643071596c80070";
        String secret = "625ea8d584ea1f15b0ea862beccbefd5";
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        System.out.println(".................");
        String sessionKey = "";
        String openId = "";
        if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
            String sessionData = responseEntity.getBody();
            System.out.println(sessionData);
            //对数据进行解析，获取session_key和openid\
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("cry",sessionData);
            JSONObject cryJson = jsonObject.getJSONObject("cry");
            sessionKey = cryJson.getString("session_key");
            openId = cryJson.getString("openid");
            System.out.println(sessionKey);
            System.out.println(openId);
            System.out.println("*****************************");
        }
        System.out.println("...........................................");
        Map<String,String> map = new HashMap<>();
        map.put("sessionKey",sessionKey);
        map.put("openId",openId);

        return new Result<>().OK(map);
    }

    /**
     * 通过用户id获取角色信息
     * @param userId
     * @return
     */
    @RequestMapping("/getRoleByUserId")
    public Result<List<SysRole>> getRoleByUserId(String userId) {
        //获取用户角色关联表
        QueryWrapper<SysUserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.eq("user_id",userId);
        List<SysUserRole> userRoleList = sysUserRoleService.list(userRoleQueryWrapper);
        List<SysRole> sysRoleList = new ArrayList<>();
        Result<List<SysRole>> result = new Result<>();
        if (userRoleList == null) {
            result.error500("未找到用户相关角色信息");
        }else{
            //获取用户角色信息
            for (SysUserRole sysUserRole : userRoleList) {
                SysRole sysRole = sysRoleService.getById(sysUserRole.getRoleId());
                if (sysRole != null) {
                    sysRoleList.add(sysRole);
                }
            }
            result.setResult(sysRoleList);
        }
        return result;
    }
}
